<template>

  <div class="flex flex-col h-full" style="background-color: #ffffff; box-sizing: border-box;">

    <div :class="{'watermark':true, 'hideWater': visibleDetail}" id="watermark">
      <!-- deecp.cn -->
    </div>
    <AddUserStockView ref="addUserStockViewRef" @refreshZixuanStatus="refreshZixuanStatus" />
    <div class="flex justify-between mb-2 " style="padding:.5em 0 0 1em; box-sizing: border-box;">
      <!-- 策略选择&策略配置-->
      <div>
        <a-select placeholder="策略模版" size="large" class="dropdown-option" 
          :options="mbListOptions" @change="mbChange" allowClear>

        </a-select>
        <button @click="openzhibiaoconfig" class="filter-button" style="margin-left: .5em;">
          <!-- 筛选器 -->
          <div style="display: flex; flex-direction: row; justify-content: center; align-items: center;">
            <svg style="display: flex;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
              fill="none" version="1.1" width="13" height="12"
              viewBox="0 0 13 12">
              <g>
                <path
                  d="M2.78,10.6683C3.06227,9.86833,3.81836,9.33333,4.66667,9.33333C5.51498,9.33333,6.27107,9.86833,6.55333,10.6683L13.3333,10.6683L13.3333,12.0016L6.55333,12.0016C6.27107,12.8016,5.51498,13.3366,4.66667,13.3366C3.81836,13.3366,3.06227,12.8016,2.78,12.0016L0,12.0016L0,10.6683L2.78,10.6683ZM6.78,6.00163C7.06227,5.20166,7.81836,4.66667,8.66667,4.66667C9.51498,4.66667,10.2711,5.20166,10.5533,6.00163L13.3333,6.00163L13.3333,7.33497L10.5533,7.33497C10.2711,8.13494,9.51498,8.66993,8.66667,8.66993C7.81836,8.66993,7.06227,8.13494,6.78,7.33497L0,7.33497L0,6.00163L6.78,6.00163ZM2.78,1.33497C3.06227,0.534993,3.81836,0,4.66667,0C5.51498,-7.94729e-8,6.27107,0.534994,6.55333,1.33497L13.3333,1.33497L13.3333,2.6683L6.55333,2.6683C6.27107,3.46827,5.51498,4.00327,4.66667,4.00327C3.81836,4.00327,3.06227,3.46827,2.78,2.6683L0,2.6683L0,1.33497L2.78,1.33497Z"
                  fill-opacity="1" />
              </g>
            </svg>
            <span style="display: flex;vertical-align: middle;margin-left:5px;">筛选器</span>
          </div>
        </button>
        <button :class="{'filter-button': true}" style="margin-left: .5em;" @click="addUserStocksClick" v-if="selectedRowKeys.length>0">
          <span style="display: flex;vertical-align: middle;margin-left:5px;">添加自选</span>
        </button>

        <a href="javascript:void(0);" v-if="zhibiaoFilter" @click="clearZhiBiaoFilter"
          style="margin-left: .5em;">清除筛选条件</a>
      </div>
      <!-- 列表方式 &搜索框-->
      <div class="flex items-center" style="margin-right: .5em;">

        <button :class="{'filter-button2': true, 'active': listtype=='0', 'normal-stock-list': true}" style="margin-left: .5em;" @click="switchStockListView('0')">
          <BarsOutlined style="font-size: 16px;" /><span style="font-size: 14px;">&nbsp;&nbsp;股票列表</span>
        </button>
        <button :class="{'filter-button2': true, 'active': listtype=='1','multi-stock-list':true}" style="margin-left: .5em;" @click="switchStockListView('1')">
          <AppstoreOutlined style="font-size: 16px;" /><span style="font-size: 14px;">&nbsp;&nbsp;多股同列</span>
        </button>

        <a-input placeholder="搜索股票代码/名称/拼音关键字" v-model:value="searchStockCode" size="large"
          class="search-stock-code"
          style=""
           @pressEnter="onSearch">
          <template #prefix>
            <search-outlined />
          </template>
        </a-input>
      </div>
    </div>
    <div class="flex flex-1" style="flex-direction: row;" v-if="listtype == '0'">

      <div style="display: flex;flex:1;border-right: 1px solid #f1f1f1; min-width: 0;padding-left:1em;"
        class="bg-white">
        <s-table ref="mytableref" 
          :row-height="75"
          :columns="columns" 
          :data-source="data" 
          row-key="stockCode"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, columnWidth:28 }"
          :scroll="{ x: scroll_x, y: scroll_y }" 
          :pagination="false" 
          @change="stockTableChange"
          @columnDragEnd="columnDragEndEvent"
          :columnDrag="true"
          :loading="listLoading">

          <template #headerCell="{ column }">
            <template v-if="column.key === 'config'">
              <span @click="showcolconfig" class="cursor-pointer">
                <SettingOutlined />
              </span>
            </template>
          </template>

          <template #bodyCell="item">

            <template v-if="item?.column.key === 'stock_name'">
              <div class="flex flex-row">
                <div class="flex" style="margin-right: 8px;">
                  <a-avatar :src="item.record.logo" />
                </div>
                <div class="flex flex-col justify-center cursor-pointer" @click="opendetail(item.record)">
                  <span style="color:rgb(2, 95, 255);font-size: .9em;">{{ item.record.stockName }}</span>
                  <span style="font-size: .8em;text-align: left;font-family: Source Han Sans;font-feature-settings: 'kern';">{{ item.record.stockCode }}</span>
                </div>
              </div>
            </template>

            <template v-if="item?.column.type === '5'">
              <div v-if="!visibleDetail">
                <span v-if="item.record[item.column.dataIndex] > 0" class="rate-zb-block stock-rate-zb-red">
                  <span v-if="item.column.key!='turnover_rate'">+</span> {{ item.record[item.column.dataIndex] }}%</span>
                <span v-else class="rate-zb-block stock-rate-zb-green">
                  {{ item.record[item.column.dataIndex] }}%</span>
              </div>
              <div v-else>
                <span v-if="item.record[item.column.dataIndex] > 0" class="stock-text-red">
                  <span v-if="item.column.key!='turnover_rate'">+</span>{{ item.record[item.column.dataIndex] }}%</span>
                <span v-else class="stock-text-green">
                  {{ item.record[item.column.dataIndex] }}%</span>
              </div>
            </template>
            <template v-if="item?.column.key === 'close'">
              <div v-if="item.record.riseAndFall > 0" class=" flex justify-center m-1 stock-text-red rounded ">
                {{ item.record.close }}</div>
              <div v-else class="text-green-500 flex justify-center m-1 text-white rounded ">
                {{ item.record.close }}</div>
            </template>

            <template v-if="item.column.type === '6'">
              {{ !item.record[item.column.dataIndex]?'':item.record[item.column.dataIndex].toFixed(0) }}
              <RenderChartItem :dataArr="item.record[item.column.dataIndex + 'Arr']" />
            </template>

            <template v-if="item.column.type === '7'">
                <div style="display: flex;flex-direction: row; margin-left: 1em;">
                  <RenderCandleItem :open="item.record[item.column.dataIndex + 'Open']"
                    :close="item.record[item.column.dataIndex + 'Close']"
                    :high="item.record[item.column.dataIndex + 'High']"
                    :low="item.record[item.column.dataIndex + 'Low']" />
                  <div style="margin-left: .5em;">{{ item.record[item.column.dataIndex] }}%</div>
                </div>
            </template>

            <template v-if="item?.column.key === 'turnover'">
              {{ (item.record.turnover / 100000000).toFixed(2) }}亿
            </template>

            <template v-if="item?.column.key === 'config'">
              <span></span>
            </template>

          </template>
        </s-table>
      </div>

      <!--弹出层显示股票详细-->
      <div class="flex flex-row bg-white" style="flex:3;min-width: 0;height: 100%;border-right: 1px solid #f1f1f1;" v-if="visibleDetail" ref="screenShot">
        <div class="flex flow-col" style="flex-direction: column;flex:6; min-width: 0;">
          <div class="flex" style="height: 100%;">
            <chartView ref="chartViewRef" :stock="currentStockData" @openStockDrawer="openDrawer"
              @settingChange="onSettingChange" @indicatorChange="onIndicatorChange"
              @hideStockPane = "hideStockPane"
              @addStock2SelfPage="addStock2SelfPage"
              @deleteStock2SelfPage="deleteStock2SelfPage"
              @screenShot="screenShotEvent"
              :widthRate="0.67"
              :mainIndicators="selectedMainIndicator" :subIndicators="selectedSubIndicator"
              :settingItems="settingItems" />
          </div>
        </div>

        <div v-if="drawerVisbile" class="flex flex-col bg-white right_stock_info_ban" 
          style="flex: 2.8;min-width: 0;flex-direction: column;">
          <div class="flex" style="padding:.5em 0 .5em .8em;  font-weight: 500;font-size: 1.2em;">个股数据</div>
          <div :style="rightStockInfoStyle" class="flex">

            <div class="flex stock-info-bank stock-base-info" 
              style="background-color: #f1f1f1;margin:1em;padding:.5em;border-radius: .3em;margin-top: 0;
                flex-direction: column;flex:2">
              <div class="flex" style="padding: .2em 0 .2em .5em">公司基本信息</div>
              <div class="flex flex-col" style="background-color: #fff;padding:.5em; border-radius: .5em; margin:.3em">
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">交易所</span>
                  <span class="stock-info-bank-value">{{ currentStockData.exchange==2?'深圳证券交易所': currentStockData.exchange==1?'上海证券交易所':currentStockData.exchange==3?'北京证券交易所':'--'}}</span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">营业收入</span>
                  <span class="stock-info-bank-value">{{ currentStockData.totalOperatingRevenueFirst?(currentStockData.totalOperatingRevenueFirst/100000000).toFixed(2)+'亿':'--' }}</span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">净利润</span>
                  <span class="stock-info-bank-value">{{ currentStockData.netProfitFirst?(currentStockData.netProfitFirst / 100000000).toFixed(2)+'亿':'--' }}</span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">净利润增长率</span>
                  <span class="stock-info-bank-value">{{ currentStockData.netProfitYoyGrowthRateFirst }}%</span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">净资产收益率</span>
                  <span class="stock-info-bank-value">{{ currentStockData.returnOnEquityFirst }}%</span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">动态市盈率(PE)</span>
                  <span class="stock-info-bank-value">{{ currentStockData.PE }}</span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">市值</span>
                  <span class="stock-info-bank-value">{{ getSZ(currentStockData.FMC) }}&nbsp;/&nbsp;{{ getSZ(currentStockData.TMC) }}</span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">行业</span>
                  <span class="stock-info-bank-value">{{ currentStockData.industry }}</span>
                </div>
              </div>
            </div>
  
            <div class="flex stock-info-bank flex-col"
              style="background-color: #f1f1f1;margin:1em;padding:.5em;margin-top: 0;border-radius: .3em;flex:1">
              <div class="flex" style="padding: .2em 0 .2em .5em">动量评级</div>
              <div class="flex flex-col" style="background-color: #fff;padding:.5em; border-radius: .5em; margin:.3em">
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">个股是否走强</span>
                  <span class="stock-info-bank-value">
                    <check-outlined v-if="currentStockData.stockUpTrend=='是'" style="color:green" />
                    <close-outlined v-else style="color:red" />
                  </span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">个股是否强势</span>
                  <span class="stock-info-bank-value">
                    <check-outlined v-if="currentStockData.stockStrongTrend=='是'" style="color:green" />
                    <close-outlined v-else style="color:red" />
                  </span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">板块是否走强</span>
                  <span class="stock-info-bank-value">
                    <check-outlined v-if="currentStockData.sectorUpTrend=='是'" style="color:green" />
                    <close-outlined v-else style="color:red" />
                  </span>
                </div>
                <div class="stock-info-bank-item">
                  <span class="stock-info-bank-label">板块是否强势</span>
                  <span class="stock-info-bank-value">
                    <check-outlined v-if="currentStockData.sectorStrongTrend=='是'" style="color:green" />
                    <close-outlined v-else style="color:red" />
                  </span>
                </div>
              </div>
            </div>
  
            <div class="flex stock-info-bank flex-col"
              style="background-color: #f1f1f1;margin:1em;padding:.5em;margin-top: 0;border-radius: .3em;flex:2;
              height:100%;overflow-y: scroll;margin-bottom: 0;">
              <div class="flex" style="padding: .2em 0 .2em .5em">{{currentStockData.maxSectorRsName}}(RS {{ !currentStockData.maxSectorRs?'--':currentStockData.maxSectorRs.toFixed(0) }})</div>
              <div class="flex recommend-pane flex-col" 
                style="background-color: #fff;padding:.6em; border-radius: .5em; margin:.3em;overflow-y: scroll;">
                <div class="flex stock-info-bank-item" style="justify-content: center;
                  align-items: center;padding:.5em 0;color: #000; flex-direction: row;">
                  <span class="stock-info-ai-value" style="flex:1.2">&nbsp;股票名</span>
                  <span class="stock-info-ai-value" style="flex:1.2">&nbsp;&nbsp;&nbsp;&nbsp;涨跌幅</span>
                  <span class="stock-info-ai-value" style="flex:0.8">&nbsp;&nbsp;RS</span>
                  <span class="stock-info-ai-value" style="flex:0.8">强势</span>
                </div>
                <div class="flex stock-info-bank-item" style="justify-content: center;align-items: center;flex-direction: row;"
                  v-for="item in aiRecommendStockList" :key="item.stockCode">
                  <span class="stock-info-ai-value" style="color: #025FFF;cursor: pointer;flex:1.2;
                    overflow: hidden;white-space: nowrap;text-overflow: ellipsis;"
                    @click="viewAiStock(item.stockCode)">{{ item.stockName }}</span>
                  <span class="stock-info-ai-value" style="flex:1.2">
                    <span v-if="item.riseAndFall > 0" class="stock-text-red">&nbsp;&nbsp;&nbsp;{{ item.riseAndFall }}%</span>
                    <span v-else class="stock-text-green">&nbsp;&nbsp;&nbsp;{{ item.riseAndFall }}%</span>
                  </span>
                  <span class="stock-info-ai-value" style="flex: 0.8">&nbsp;&nbsp;&nbsp;{{ !item.stockWeighted252dRS?'--':item.stockWeighted252dRS.toFixed(0) }}</span>
                  <span class="stock-info-ai-value" style="flex: 0.8">
                    <span v-if="item.stockStrongTrend">&nbsp;&nbsp;&nbsp;是</span>
                    <span v-else>&nbsp;&nbsp;&nbsp;否</span>
                  </span>
                </div>
              </div>
            </div>
            
          </div>

        </div>


      </div>

    </div>
    
    <!-- 多股同列 -->
    <div v-else class="flex flex-col flex-1 bg-white">
      <stockViewList :containerHeight="containerHeight" 
        :stockCode="searchStockCode"
        :filterZbs="filterZbs"
        :columnOrders="columnOrders" 
        ref="stockViewListRef" />
    </div>


    <!-- 弹出列显示配置抽屉 -->
    <a-drawer placement="right" width="25%" :closable="false" :maskClosable="true" v-model:visible="visibleConfig">
      <ColConfig :unshowlist="unshowlist" :showlist="columns" @addOrRemoveCols="addOrRemoveCols" />
    </a-drawer>

    <!-- 弹出列指标抽屉 -->
    <a-drawer placement="right" width="40%" :closable="false" :maskClosable="true" v-model:visible="visibleZhibiao">
      <ZhibiaoConfig @filterStockOfZhibiao="onFilterStockOfZhibiao" ref="zhibiaoConfigRevf"/>
    </a-drawer>

  </div>

</template>
<script lang="ts">
import STable from '@surely-vue/table';
import { message, Popconfirm, Drawer, Radio, Input, Select, Table,Avatar, RadioGroup, Button, Modal, Checkbox } from 'ant-design-vue';

import { ref, defineComponent, onMounted, onUnmounted, h } from 'vue';
import { useRoute } from 'vue-router'
import {
  SettingOutlined, ControlOutlined, BarsOutlined, AppstoreOutlined, SearchOutlined, PlusSquareFilled,
  CheckOutlined, CloseOutlined
} from '@ant-design/icons-vue';
import { getTableColumns } from '/@/api/stock/selfstock';
import { getStocks, getStockAiRecommendStockList, getStock } from '/@/api/stock/stockDailyDao';
import { updateColumnSn } from '/@/api/stock/userColumnsDao';
import { addUserStocks, getUserPages, addUserPage, deleteUserPage, stockInUserStock, deleteUserStock } from '/@/api/stock/userStocksDao';
import { dpTmpjsonFrontSave, frontlist, frontdelusermb } from '/@/api/dp/stocktmp/dpTmpjson';
import chartView from '../chart/chart_view.vue';
import ZhibiaoConfig from '/@/views/selfstock/zhibiaoconfig.vue';
import stockViewList from './stock_view_list.vue'
import ColConfig from '/@/views/selfstock/configcol.vue';
import RenderCandleItem from "../stock/components/RenderCandleItem.vue";
import RenderChartItem from "../stock/components/RenderChartItem.vue";
import AddUserStockView from './add_user_stock.vue'

import { init, dispose, registerOverlay, registerIndicator, registerFigure, TooltipIconPosition } from 'klinecharts';
import { getCurrentUserId } from '../../utils/currentUser.ts';
import html2canvas from 'html2canvas';
import domtoimage from 'dom-to-image';

export default {
    components: {
      AButton: Button,
      ADrawer: Drawer,
      ARadio: Radio,
      AInput: Input,
      ASelect: Select,
      ATable: Table,
      AAvatar: Avatar,
      Popconfirm: Popconfirm,
      ARadioGroup: RadioGroup,
      AModal: Modal,
      ACheckbox: Checkbox,
      STable: STable
    },
  };
</script>

<script lang="ts" setup>

import { nextTick } from 'vue';
const route = useRoute()

const selectcount=ref(0);
const columns = ref([]);
var tableContainer;
const stockViewListRef = ref();
const addUserStockViewRef = ref();
const zhibiaoConfigRevf =ref();

const containerHeight = ref(0);
const pageSize = ref(20);
const currentPageNo = ref(1);
const fixedScoller = ref(false);
const listLoading = ref(false);
const chartViewRef = ref();
const visibleZhibiao = ref(false);

const zhibiaoFilter = ref(false);
const rightStockInfoStyle = ref({
  "flex-direction":"column",
  "height":'100%',
  "overflow-y": "hidden"
})


//策略模板list
const mbList = ref([]);
const mbListOptions = ref([]);
const selectedRowKeys = ref([]);
const filterZbs = ref();
const searchStockCode = ref('');
const columnOrders = ref();
const screenShot = ref();

/**
 * 计算市值
 */
function getSZ(sz){
  if(!sz){
    return ''
  }
  let ysz = sz/100000000;
  if(ysz>=10000){
    return (ysz/10000).toFixed(2)+'万亿';
  }
  return ysz.toFixed(2)+'亿';
}

function screenShotEvent(){
  // domtoimage.toPng(screenShot.value)
  //   .then(function (dataUrl) {
  //     const downloadLink = document.createElement('a');
  //     downloadLink.href = dataUrl;
  //     downloadLink.download = 'screenshot.png';
  //     downloadLink.click();
  //   })
  //   .catch(function (error) {
  //       console.error('oops, something went wrong!', error);
  //   });
  html2canvas(screenShot.value,{
  logging: false, //日志开关，便于查看html2canvas的内部执行流程
  width: screenShot.value.clientWidth, //dom 原始宽度
  height: screenShot.value.clientHeight,
  scrollY: 0,
  scrollX: 0,
  allowTaint:true,
  useCORS: true// 【重要】开启跨域配置
}).then((canvas)=>{
    const image = canvas.toDataURL('image/png');
    const downloadLink = document.createElement('a');
    downloadLink.href = image;
    downloadLink.download = 'screenshot.png';
    downloadLink.click();
  });
}

function openzhibiaoconfig() {
  visibleZhibiao.value = true;
}

function onSelectChange(keys) {
  selectedRowKeys.value = keys;
}
function switchStockListView(value) {
  listtype.value = value;
  if (listtype.value == '0') {
    stockListLoad();
    nextTick(() => {
      tableContainer = mytableref.value.$el.querySelector('.ant-table-body');
      if (tableContainer) {
        tableContainer.addEventListener('scroll', handleScroll);
      }
      if (chartViewRef.value) {
        chartViewRef.value.switchStockKline(currentStockData.value);
        chartViewRef.value.changeRsStrongPaneWidth(drawerVisbile.value)
      }
    });
  }
}

function customHeader(columns) {
  columns.forEach((e, index) => {
    if (index > 1) {
      columns[index].className = 'tableHeaderClass';
    }
  });
}

function resetColumnWidth(columns) {
  let pw = window.innerWidth - 350;
  let colWidth = pw / (columns.length-1);
  if(colWidth<100) {
    colWidth = 100;
  }
  for (var i = 0; i < columns.length; i++) {
    let column = columns[i];
    if(column.dataIndex=='config') {
      continue;
    }
    if(column.dataIndex=='stockName') {
      column.width = 150;
    }else {
      column.width = colWidth;
    }
  }
}

async function initColumns() {
  let res = await getTableColumns({},{
    "userId": getCurrentUserId()
  });
  //设置不显示的列用于弹窗展示
  unshowlist.value = res.unshowlist;
  let mycolumns = res.showlist;
  resetColumnWidth(mycolumns);
  for (var i = 0; i < mycolumns.length; i++) {
    var column = mycolumns[i];
    if(column.dataIndex=='stockName') {
      column.fixed = 'left';
    }
    column.sortDirections = ['descend', 'ascend'];
    column['align'] = 'center';
    columns.value.push(column);
  }
  let configColumn = {
    title: 'Action',
    key: 'config',
    align:'left',
    dataIndex:'config',
    ellipsis: true,
    fixed: 'right',
    type:1,
    width: window.innerWidth<1300 ? 56 : 48
  };

  columns.value.push(configColumn);
}

//获取列表数据

const data = ref([]);

async function onSearch() {
  currentPageNo.value = 1;
  if(listtype.value=='1') {
    stockViewListRef.value.searchStockListByStockCode(searchStockCode.value);
  } else if(listtype.value=='0') {
    stockListLoad();
  }
}

function stockTableChange(p, f, order) {
  columnOrders.value = order.order?order:null;
  currentPageNo.value = 1;
  stockListLoad({})
}

/**
 * @page 分页参数
 * @params null
 * @orders 排序
 * @mbid 模板json
 */
async function stockListLoad(params = {}) {
  listLoading.value = true;
  let stockFilter = localStorage.getItem('stockFilter');
  if(stockFilter){
    stockFilter = JSON.parse(stockFilter);
    zhibiaoFilter.value = true;
    if(stockFilter.zbName) {
      selectedMainIndicator.value.push(stockFilter?.zbName?.toLowerCase())
    }
  }
  var queryParam = {
    "pageNo": currentPageNo.value,
    "pageSize": pageSize.value,
    "stockCode": searchStockCode.value||stockFilter?.stockCode,
    "maxSectorRsName":stockFilter?.maxSectorRsName,
    "extraConditions": stockFilter?.extras
  }
  if (columnOrders.value) {
    queryParam['order'] = columnOrders.value.order ? (columnOrders.value.order == 'ascend' ? "asc" : "desc") : "";
    queryParam['orderBy'] = columnOrders.value.columnKey ? columnOrders.value.columnKey : ""
  }
  if (filterZbs.value) {
    queryParam['tiaojianList'] = filterZbs.value;
  }
  if(stockFilter&&stockFilter.zbFilter){
    let condition = [{'tiaojianchildlist':[stockFilter.zbFilter]}]
    queryParam['tiaojianList'] = JSON.stringify(condition);
  }
  let response = await getStocks(params, queryParam);
  let datas = response['data'];
  let resultCode = response['resultCode'];
  listLoading.value = false;
  if(resultCode=='FAIL') {
    message.error(response['msg']);
    return;
  }
  selectcount.value=datas.count;
  currentPageNo.value = datas['pageNo'];

  if (currentPageNo.value == 1) {
    data.value = datas['list'];
  } else {
    if (datas['list'] && datas['list'].length > 0) {
      let newDataArr = [...data.value].concat(datas['list'])
      data.value = newDataArr;
    }
  }

  if (currentPageNo.value == 1 && tableContainer) {
    tableContainer.scrollTop = 0;
  }
}
/**
 * 模板选股调用
 * @param zhiBiaoList 指标list
 */
async function onFilterStockOfZhibiao(zhiBiaoList) {
  currentPageNo.value = 1;
  searchStockCode.value = '';
  filterZbs.value = zhiBiaoList;
  await stockListLoad({});
  zhibiaoFilter.value = true;
  zhibiaoConfigRevf.value.refreshFilterTotalData(selectcount.value);
}

function clearZhiBiaoFilter() {
  zhibiaoFilter.value = false;
  currentPageNo.value = 1;
  filterZbs.value = null;
  localStorage.setItem('stockFilter','');
  stockListLoad();
}

//配置列相关
const visibleConfig = ref(false);
const drawerVisbile = ref(true);

const unshowlist = ref([]);
function showcolconfig() {
  visibleConfig.value = true;
}

function addOrRemoveCols(obj) {
  if (isColumnExists(obj.key)) {
    //移除
    removeColumn(obj.key);
    scroll_x.value = scroll_x.value - obj.width;
    resetColumnWidth(columns.value);
  } else {
    let tempCols = columns.value;
    let length = columns.value.length;
    let sn = obj.sn ? obj.sn : length - 1;
    tempCols.splice(sn, 0, obj);
    scroll_x.value = scroll_x.value + obj.width;
    columns.value = [...tempCols];
    resetColumnWidth(columns.value);
  }
  
}

function isColumnExists(key) {
  return columns.value.some(a => a.key === key);
}

function removeColumn(key) {
  columns.value = columns.value.filter(col => col.key !== key);
}

//x方向滚动条参数设置
const scroll_x = ref(1000);
const scroll_y = ref(500);

//点击股票相关
const visibleDetail = ref(false);
const mytableref = ref(null);

//定义3列
const oldcolumns = ref([]);
const oldscroll_x = ref(0);

// 当前股票数据
const currentStockData = ref({
  stockCode: '',
  stockName: ''
});

const aiRecommendStockList = ref([]);

function getAiRecommendStockList() {
  getStockAiRecommendStockList({
    "stockCode": currentStockData.value.stockCode
  }).then(list => {
    if (list && list.length > 0) {
      aiRecommendStockList.value = list;
    } else {
      aiRecommendStockList.value = [];
    }
  });
}

async function viewAiStock(stockCode) {
  let stockData = await getStock({
    "stockCode": stockCode
  });
  opendetail(stockData);
}

function resetSelectMainIndicators(obj) {
  
  // if(obj.isVcp=='是') {
  //   selectedMainIndicator.value.push('vcp');
  // }
  // if(obj.isCupAndHandle=='是') {
  //   selectedMainIndicator.value.push('cup_and_handle');
  // }
  //   if(obj.isCupAndHandle=='是') {
  //   selectedMainIndicator.value.push('cup_and_handle');
  // }
  //   if(obj.isTriangle=='是') {
  //   selectedMainIndicator.value.push('triangle');
  // }
  //   if(obj.isWedge=='是') {
  //   selectedMainIndicator.value.push('wedge');
  // }
  //   if(obj.isFlag=='是') {
  //   selectedMainIndicator.value.push('flag');
  // }
  //   if(obj.isDoubleBottom=='是') {
  //   selectedMainIndicator.value.push('double_bottom');
  // }
  //     if(obj.isInverseHs=='是') {
  //   selectedMainIndicator.value.push('inverse_hs');
  // }
}

async function opendetail(obj) {
  //判断是否已经显示详情界面
  resetSelectMainIndicators(obj)
  if (!visibleDetail.value) {
    visibleDetail.value = true;
    oldcolumns.value = columns?.value;
    oldscroll_x.value = scroll_x.value;

    let stockNameCol = {...columns.value.find(item=>item.dataIndex=='stockName')};
    stockNameCol['width'] = 110;
    let closeCol = {...columns.value.find(item=>item.dataIndex=='close')};
    closeCol['width'] = 70;
    let riseAndFallCol = {...columns.value.find(item=>item.dataIndex=='riseAndFall')};
    riseAndFallCol['width']=80;

     if(pageWidth.value>=1520) {
      columns.value = [stockNameCol, closeCol, riseAndFallCol];
     } else {
      columns.value = [stockNameCol, riseAndFallCol];
     }

    scroll_x.value = (pageWidth.value - 130) / 4;
    drawerVisbile.value = true;

    
  }
  currentStockData.value = { ...obj };
  selectedRowKeys.value = [obj.stockCode];

  getAiRecommendStockList();
  nextTick(() => {
    if (chartViewRef.value) {
      chartViewRef.value.switchStockKline(currentStockData.value);
      chartViewRef.value.changeRsStrongPaneWidth(drawerVisbile.value);
      chartViewRef.value.resetSelectIndicators(selectedMainIndicator.value);
    }
  });
}

function hideStockPane() {
  columns.value = oldcolumns.value;
  visibleDetail.value = false;
  scroll_x.value = oldscroll_x.value;
  chartViewRef.value.disposeChart();
  drawerVisbile.value = false;
}

const listtype = ref("0");


//多股同列
const pageHeight = ref(0);
const pageWidth = ref(0);

onMounted(async () => {
  // 获取页面高度
  window.addEventListener('resize', handleResize);
  tableContainer = mytableref.value.$el.querySelector('.surely-table-vertical-scroll-viewport');
  if (tableContainer) {
    tableContainer.addEventListener('scroll', handleScroll,);
  }
  await initColumns();
  loadMbList();
  await stockListLoad();
  nextTick(()=>{
    pageHeight.value = window.innerHeight;
    pageWidth.value = window.innerWidth;
    scroll_y.value = pageHeight.value - 140;
    scroll_x.value = pageWidth.value - 200;
    rightStockInfoStyle.value['max-height'] = (pageHeight.value - 125) + 'px';
  });
});

function handleScroll() {
  if (fixedScoller.value) {
    return;
  }
  const scrollPosition = tableContainer.scrollTop;
  const bottomOffset = tableContainer.scrollHeight - scrollPosition - tableContainer.clientHeight;
  if (Math.abs(bottomOffset) < 5 && !listLoading.value) {
    currentPageNo.value = currentPageNo.value + 1;
    stockListLoad();
  }
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  dispose('chart');
  saveChartConfigDatas();
  if (tableContainer) {
    tableContainer.removeEventListener('scroll', handleScroll);
    containerHeight.value = tableContainer.clientHeight;
  }
  localStorage.setItem('stockFilter', '');
});

/**
 * 查询策略模板
 */
function loadMbList() {
  frontlist().then(datas => {
    if (datas && datas.length > 0) {
      for (var i = 0; i < datas.length; i++) {
        mbList.value.push(datas[i]);
        var option = {
          label: datas[i].tmpname,
          value: datas[i].id
        };
        mbListOptions.value.push(option);
      }
    }
  });
}
/**
 * 基于策略模板选择股票
 * @param value 模板id
 */
function mbChange(value) {
  var mb = mbList.value.find(item => item['id'] == value);
  currentPageNo.value = 1;
  filterZbs.value = mb ? mb['tmpjson'] : ''
  stockListLoad();
}

const handleResize = () => {
  pageHeight.value = window.innerHeight;
  console.log(" pageHeight.value ===" + pageHeight.value);
  scroll_y.value = pageHeight.value - 160;
};

const selectedMainIndicator = ref(['stockWeighted252dRS', 'indicator_collects']);
const selectedSubIndicator = ref(['VOL']);
const settingItems = ref([
  {
    name: "蜡烛图类型", type: "select", options: [
      { label: "全实心", value: "candle_solid" },
      { label: "全空心", value: "candle_stroke" },
      { label: "涨空心", value: "candle_up_stroke" },
      { label: "跌空心", value: "candle_down_stroke" },
      { label: "OHLC", value: "ohlc" },
      { label: "面积图", value: "area" }
    ],
    key: "candle.type",
    defaultValue: "candle_solid",
    value: "candle_solid"
  },
  { name: "最新价显示", type: "switch", options: [], key: "candle.priceMark.last.show", defaultValue: true, value: true },
  { name: "最高价显示", type: "switch", options: [], key: "candle.priceMark.high.show", defaultValue: true, value: true },
  { name: "最低价显示", type: "switch", options: [], key: "candle.priceMark.low.show", defaultValue: true, value: true },
  {
    name: "指标最新值显示",
    type: "switch",
    options: [],
    key: "indicator.lastValueMark.show",
    defaultValue: false,
    value: false
  },
  {
    name: "价格轴类型", type: "select", options: [
      { label: "线性轴", value: "normal" },
      { label: "百分比轴", value: "percentage" },
      { label: "对数轴", value: "log" },
    ],
    key: "yAxis.type",
    defaultValue: "normal",
    value: "normal"
  },
  { name: "倒置坐标", type: "switch", options: [], key: "yAxis.reverse", defaultValue: false, value: false },
  { name: "网格线显示", type: "switch", options: [], key: "grid.show", defaultValue: true, value: true },
]);

function openDrawer() {
  drawerVisbile.value = !drawerVisbile.value;
  nextTick(() => {
    chartViewRef.value.scrollToCurrent();
    chartViewRef.value.changeRsStrongPaneWidth(drawerVisbile.value);
  });
}

function onSettingChange(data) {
  settingItems.value = data;
}

function onIndicatorChange(indicator: string, isDel?: boolean, isSub?: boolean) {
  if (isSub) {
    selectedSubIndicator.value = [...selectedSubIndicator.value.filter(item => item != indicator)];
    if (isDel) {

    } else {
      selectedSubIndicator.value.push(indicator)
    }
  } else {
    if (isDel) {
      selectedMainIndicator.value = [...selectedMainIndicator.value.filter(item => item != indicator)]
    } else {
      selectedMainIndicator.value.push(indicator)
    }
  }
}

function saveChartConfigDatas() {
  localStorage.setItem('selectedSubIndicator', JSON.stringify(selectedSubIndicator.value));
  localStorage.setItem('selectedMainIndicator', JSON.stringify(selectedMainIndicator.value));
  localStorage.setItem('settingItems', JSON.stringify(settingItems.value));
}

/**
 * 加自选
 */
function addUserStocksClick() {
  if(selectedRowKeys.value.length==0) {
    message.error('请选择股票');
    return;
  }
  addUserStockViewRef.value.showAddUserStockView(1, selectedRowKeys.value)
}

function addStock2SelfPage() {
  if(selectedRowKeys.value.length==0) {
    message.error('请选择股票');
    return;
  }
  addUserStockViewRef.value.showAddUserStockView(2, [currentStockData.value.stockCode]);
}

function refreshZixuanStatus(stocks) {
  chartViewRef.value.refreshStockInZixuanStatus()
}

function deleteStock2SelfPage() {
  deleteUserStock({}, {
    'userId': getCurrentUserId(),
    'stockCodes': [currentStockData.value.stockCode]
  });
  message.success('删除成功');
}

function saveUserColumns2Server() {
  let columCodes = [];
  for(var i=0; i<columns.value.length; i++) {
    columCodes.push(columns.value[i]['key']);
  }
  updateColumnSn({},{
    "userId": getCurrentUserId(),
    "columns": columCodes
  });
}

function columnDragEndEvent() {
  setTimeout(()=>{
    saveUserColumns2Server();
  }, 500)
}

</script>

<style lang="less" scoped>

/deep/.customHeader {
  font-weight: 700;
}

.ant-table-column-title {
  font-weight: 700;
}

.stockInfo .ant-drawer-body {
  background-color: #f0f0f0;
}

.stockInfo .stock-info-bank {
  background-color: #ffffff;
  border-radius: .5em;
  padding: .5em;
  border: 1px solid #ddd;
}

.stock-info-bank-item {
  display: flex;
  padding: .2em .4em;
}

.stock-info-bank-item span {
  display: flex;
}

.stock-info-bank-label {
  color: #333;
}

.stock-info-bank-value {
  margin-left: auto;
}

.stock-info-ai-value {
  text-align: center;
  align-content: center;
  margin: 0 auto;
}

.u-item {
  padding: .5em 0;
}

.rate-zb-block {
  min-width: 68px;
  text-align: center;
  padding: 2px;
  border-radius: 4px;
  display: inline-block;
  color: #ffffff;
  font-size: 14px;
  box-sizing: border-box;
}

.ant-select-selector {
  border-radius: 8px !important;
}

.dropdown-option {
  border-radius: 5px;
  margin: 5px 0;
  display: inline-block;
}

.backBtn {
  padding: 2px 12px;
  border: 1px solid #212121;
  border-radius: 5px;
}

.backBtn:hover {
  padding: 2px 12px;
  border: 1px solid #025fff;
  color: #025fff;
}

.ant-radio-button-wrapper:not(:first-child)::before {
  width: 0 !important;
}

.ant-radio-button-wrapper {
  border-left-width: 1px !important;
}

.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {
  color: #025fff !important;
  border-color: #025fff !important;
}

.filter-button {
  background-color: #f1f1f1;
  border-radius: 5px;
  border: 0;
  padding: .6em 1.5em;
}

.filter-button.active {
  background-color: #f1f1f1;
  border-radius: 5px;
  border: 0;
  padding: .6em 1.5em;
  color: #255fff;
  border:1px solid #255fff;
}

.filter-button2 {
  background-color: #fff;
  border-radius: 5px;
  border: 0;
  padding: .6em 1.5em;
  border:1px solid #d9d9d9;
}

.filter-button2.active {
  background-color: #fff;
  border-radius: 5px;
  border: 0;
  padding: .6em 1.5em;
  color: #255fff;
  border:1px solid #255fff;
}

.filter-button svg {
  fill: #212121;
}

.filter-button:hover {
  color: #255fff;
}

.filter-button:hover svg {
  fill: #025fff;
}

.right_stock_info_ban {
  flex: 1.3;
  border: 1px solid #f1f1f1;
}

.hideWater{
  display: none !important;
}
.watermark {
  position: fixed;
  display: block;
  top: 100px;
  left: 0;
  width: 100%;
  height: 100%;
  line-height: 600px;
  padding-top: 100px;
  z-index: 9990;
  pointer-events: none;
  font-size: 120px;
  font-weight: 700;
  text-align: center;
  color: rgba(0, 0, 0, 0.06);
  transform-origin: center;
  background-image: url('/@/assets/icons/deecp-logo.svg');
  background-repeat: no-repeat;
  background-position: 50% 30%;
  background-size: 50% 50%;
  opacity: .35;
}
.stock-info-bank ::-webkit-scrollbar {
  width:0 !important;
}
:deep(.ant-modal) {
    border-radius: 16px !important;
    overflow: hidden;
}

:deep(.surely-table) {
  font-size: 15px;
 
  // Unlicensed Product   带有滚动条的table
  .surely-table-horizontal-scroll+div {
    visibility: hidden !important;
  }
 
  .surely-table-unselectable {
 
    // Powered by Surely Vue
    .surely-table-body-viewport-container+div {
      // 使用CSS的clip属性来隐藏元素。这样可以根据元素的尺寸和位置来裁剪显示区域，将其设为与元素相同大小的矩形，即可隐藏该元素。
      clip: rect(0, 0, 0, 0);
    }
 
    // Unlicensed Product   不带带有滚动条的table

  }
}

:deep(.surely-table-body .surely-table-body-cell-range-selected:not(.surely-table-body .surely-table-body-cell-inline-edit) ){
    background: none !important;
}
:deep(.surely-table-body .surely-table-body-cell-range-selected.surely-table-body-cell-range-single-cell) {
    border: 0 !important;
}

:deep(.surely-table-header-cell-title-inner) {
  font-weight: 600;
  font-size: 14px;
  color: #333;
  font-family: sans-serif;
}
.search-stock-code {
  margin-left:12px; 
  border-radius: 5px;
  width: 15em;
}


// 1222 1389 1528 1698 1910 2037
@media screen and (min-width: 1000px) {
  .recommend-pane{
    font-size: 11px;
  }
  .dropdown-option {
    width: 12em;
  }
  .stock-list-btn{
    display: none;
  }
  .searchStockCode {
    width:12em;
  }
  .stock-base-info{
    display: none ;
  }
  .multi-stock-list{
    display: none;
  }
  .normal-stock-list {
    display: none;
  }
}

@media screen and (min-width: 1100px) {
  .recommend-pane{
    font-size: 11px;
  }
  .dropdown-option {
    width: 12em;
  }
  .stock-list-btn{
    display: none;
  }
  .searchStockCode {
    width:12em;
  }
  .stock-base-info{
    display: none ;
  }
  .multi-stock-list{
    display: none;
  }
  .normal-stock-list {
    display: none;
  }
}
@media screen and (min-width: 1228px) {
  .recommend-pane{
    font-size: 12px;
  }
  .dropdown-option {
    width: 12em;
  }
  .setting-splitter{
    padding-right: 0 !important;
    margin: 0 !important;
  }
  .stock-base-info{
    display: none ;
  }
  .multi-stock-list{
    display: none;
  }
  .normal-stock-list {
    display: none;
  }
}

@media screen and (min-width: 1380px) {
  .recommend-pane{
    font-size: 13px;
  }
  .dropdown-option {
    width: 12em;
  }
  .stock-base-info{
    display: none ;
  }
  .multi-stock-list{
    display: inline-block;
  }
  .normal-stock-list {
    display: inline-block;
  }
}

@media screen and (min-width: 1520px) {
  .recommend-pane{
    font-size: 14px;
  }
  .dropdown-option {
    width: 12em;
  }
  .stock-base-info{
    display: block;
  }
  .multi-stock-list{
    display: inline-block;
  }
  .normal-stock-list {
    display: inline-block;
  }
}

@media screen and (min-width: 1680px) {
  .recommend-pane{
    font-size: 15px;
  }
  .dropdown-option {
    width: 15em;
  }
  .stock-base-info{
    display: block;
  }
  .multi-stock-list{
    display: inline-block;
  }
  .normal-stock-list {
    display: inline-block;
  }
}

@media screen and (min-width: 1900px) {
  .recommend-pane{
    font-size: 15px;
  }
  .dropdown-option {
    width: 15em;
  }
  .stock-base-info{
    display: block;
  }
  .multi-stock-list{
    display: inline-block;
  }
  .normal-stock-list {
    display: inline-block;
  }
}

@media screen and (min-width: 2000px) {
  .recommend-pane{
    font-size: 15px;
  }
  .dropdown-option {
    width: 15em;
  }
  .stock-base-info{
    display: block;
  }
  .multi-stock-list{
    display: inline-block;
  }
  .normal-stock-list {
    display: inline-block;
  }
}

@media screen and (min-width: 2200px) {
  .recommend-pane{
    font-size: 15px;
  }
  .dropdown-option {
    width: 15em;
  }
  .stock-base-info{
    display: block;
  }
  .multi-stock-list{
    display: inline-block;
  }
  .normal-stock-list {
    display: inline-block;
  }
}
</style>
